// 统一跨端导航封装
// 使用原则：默认 go() -> uni.navigateTo；需要替换当前页用 replace(); 需要清空栈用 reLaunch(); tabBar 页用 switchTab(); 仅 H5 且想保留历史可用 h5Push(true)

let _lastNav = { url: '', ts: 0 }
const NAV_MIN_INTERVAL = 350 // ms
export function go(url, opts = {}) {
  const now = Date.now()
  if (url === _lastNav.url && now - _lastNav.ts < NAV_MIN_INTERVAL) {
    return Promise.resolve({ cancelled: true, reason: 'duplicate-suppressed' })
  }
  _lastNav = { url, ts: now }
  const { replace = false, reLaunch = false, switchTab = false } = opts
  if (reLaunch) return uni.reLaunch({ url })
  if (switchTab) return uni.switchTab({ url })
  if (replace) return uni.redirectTo({ url })
  // 如果当前就在该页面则不再跳转
  try {
    if (typeof window !== 'undefined') {
      const cur = window.location.pathname || '/'
      if (cur === url) return Promise.resolve({ cancelled: true, reason: 'same-page' })
    }
  } catch(e) {}
  return uni.navigateTo({ url })
}

export function back(delta = 1) {
  try {
    uni.navigateBack({ delta })
  } catch (e) {
    // 兜底：无法后退时回首页
    uni.reLaunch({ url: '/pages/pc/index' })
  }
}

export function relaunchTo(url) { return uni.reLaunch({ url }) }
export function replace(url) { return uni.redirectTo({ url }) }
export function switchTo(url) { return uni.switchTab({ url }) }

// H5 专用：如果确实需要保留 complex history，可在调用处判断
export function h5Push(path) {
  if (typeof window !== 'undefined' && window?.history && path.startsWith('/')) {
    // 仍使用 uni.navigateTo 以保持一致，若是非 pages 路径可考虑直接 location.assign
    return uni.navigateTo({ url: path })
  }
  return go(path)
}
